package sms.main;

import sms.service.IStudentService;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 接收用户输入并执行相应命令
 */
public class CommandLineRunner {
    //服务名称与服务实现类的映射关系
    private Map<String, Object> serviceMap = new HashMap<>();
    //服务方法名称与调用服务方法的映射关系
    private Map<String, Map<String, Method>> methodMap = new HashMap<>();
    //服务名称与服务接口的映射关系
    private Map<String, Class<?>> serviceTypeMap = Map.of("student", IStudentService.class);

    public CommandLineRunner() {
        System.out.println("init begin");
        serviceTypeMap.forEach((type, clazz) -> {
            ServiceLoader.load(clazz).findFirst().ifPresent(serviceImpl -> {
                serviceMap.put(type, serviceImpl);
                methodMap.put(type, Stream.of(serviceImpl.getClass().getDeclaredMethods()).collect(Collectors.toMap(Method::getName, Function.identity())));
            });
        });
        System.out.println("init end");
    }

    /**
     * 根据用户输入数据来调用相应服务的指定方法
     *
     * @param service 服务名称
     * @param task    方法名称
     * @param args    方法参数
     */
    public void run(String service, String task, List<Object> args) {
        Object serviceImpl = serviceMap.get(service);
        Method method = this.methodMap.get(service).get(task);
        try {
            Object result = method.invoke(serviceImpl, args.toArray());
            System.out.println(result);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
